<template>
  <div class="app-container">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">  
      <el-form-item>
        <el-button type="primary" @click="check">筛选</el-button>
      </el-form-item>
      <el-collapse-transition>
        <div v-show="showCheck">
          <el-form-item label="所属公司">
            <el-select v-model="formInline.gongsiSel" @change="companyTable" placeholder="所属公司">
              <el-option v-for="val in gongsiList" :key="val.id" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备状态">
            <el-select v-model="formInline.leibieSel" placeholder="设备状态">
              <el-option v-for="val in $store.state.user.deviceClass" :key="val.value" :label="val.name" :value="val.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备用途">
            <el-select v-model="formInline.yongtuSel" placeholder="设备用途">
              <el-option v-for="val in $store.state.user.deviceUse" :key="val.value" :label="val.name" :value="val.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备分组">
            <el-select v-model="formInline.fenzuSel" placeholder="设备分组">
              <el-option v-for="val in fenzuList" :key="val.id" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备责任人">
            <el-select v-model="formInline.zerenrenSel" placeholder="设备责任人">
              <el-option v-for="val in zerenrenList" :key="val.id" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="省市区">
            <!-- <el-select v-model="formInline.shengshiquSel" @change="areaSel" placeholder="省市区">
              <el-option v-for="val in shengshiquList" :key="val.code" :label="val.name" :value="val.code"></el-option>
            </el-select> -->
            <!-- <el-cascader :options="shengshiquList" :props="{value:'id',label:'name'}" v-model="formInline.shengshiquSel"></el-cascader> -->
            <!-- <el-cascader :props="props"></el-cascader> -->
            <el-cascader
              :options="shengshiquList"
              :clearable="true"
              size="mini"
              ref="cascader"
              @change="handleItemChange"
              @active-item-change="handleItemChange"
              :change-on-select="changeOnSelect"
              :props="{children: 'child',label: 'name',value: 'main'}"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="营销模板">
            <el-select v-model="formInline.yingxiaoSel" placeholder="营销模板">
              <el-option v-for="val in yingxiaoList" :key="val.id" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-collapse-transition>
      <el-form-item>
        <el-button type="primary" @click="checkMenu">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button icon="el-icon-refresh" @click="handleReset">
      重置
    </el-button>
    <el-button type="primary" @click="handleAdd">
      新增
    </el-button>

    <el-table :data="dataList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" prop="name" label="设备名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="设备序列号">
        <template slot-scope="scope">
          {{ scope.row.deviceSn }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="设备状态">
        <template slot-scope="scope">
          {{ $store.state.user.deviceClass[scope.row.status].name }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="设备点位名称">
        <template slot-scope="scope">
          {{ scope.row.location }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="省市区">
        <template slot-scope="scope">
          {{ scope.row.area }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="设备分组名">
        <template slot-scope="scope">
          {{ scope.row.deviceGroupName }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="设备责任人名">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="设备营销模板名">
        <template slot-scope="scope">
          {{ scope.row.marketingTemplateName }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="设备用途">
        <template slot-scope="scope">
          {{ $store.state.user.deviceUse[scope.row.usage].name }}
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="240">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope,scope.$index)">
            编辑
          </el-button>
          <el-button type="primary" size="small" @click="handleTiao(scope)">
            调试
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑设备信息':'新增设备'">
      <el-form :model="role" :rules="rules" ref="ruleForm" label-width="160px" label-position="left">
        <el-form-item label="所属公司" prop="tenantId">
          <el-select :disabled="dialogType==='edit'" v-model="role.tenantId" @change="tenantIdChange" placeholder="所属公司">
            <el-option
              v-for="item in gongsiList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input :disabled="dialogType==='edit'" v-model="role.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备模板" prop="deviceTemplateId">
          <el-select :disabled="dialogType==='edit'" v-model="role.deviceTemplateId" placeholder="设备模板">
            <el-option
              v-for="item in mobanList2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择营销模板" prop="marketingTemplateId">
           <el-select v-model="role.marketingTemplateId" placeholder="选择营销模板">
            <el-option
              v-for="item in yingxiaoList2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择分组" prop="deviceGroupId">
          <el-select v-model="role.deviceGroupId" placeholder="选择分组">
            <el-option
              v-for="item in fenzuList2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择责任人" prop="userId">
          <el-select v-model="userId" @change="getUserName" placeholder="选择责任人">
            <el-option
              v-for="item in zerenrenList2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备序列号" prop="deviceSn">
          <el-input :disabled="dialogType==='edit'" v-model="role.deviceSn" placeholder="请输入设备序列号" />
        </el-form-item>
        <el-form-item label="所在省市区" prop="shengshiqu">          
          <el-cascader
            :options="shengshiquList"
            :clearable="true"
            size="mini"
            ref="cascader"
            @change="handleItemChange"
            @active-item-change="handleItemChange"
            :change-on-select="changeOnSelect"
            :props="{children: 'child',label: 'name',value: 'main'}"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="设备点位名称" prop="location">
          <el-input v-model="role.location" placeholder="设备点位名称" />
        </el-form-item>
        <el-form-item label="设备用途" prop="usage">
          <el-select v-model="role.usage" placeholder="请选择设备用途">
            <el-option
              v-for="item in $store.state.user.deviceUse"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select v-model="role.status" placeholder="请选设备状态">
            <el-option
              v-for="item in $store.state.user.deviceClass"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">
          取消
        </el-button>
        <el-button type="primary" @click="confirm('ruleForm')">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFillTiaoshi" title="设备调试">
      <el-form :model="role" :rules="rules" label-width="160px" label-position="left">
        <el-form-item label="选择调试类型" prop="adminName">
          <el-select v-model="tiaoVal" placeholder="选择调试类型">
            <el-option
              v-for="item in tiaoshiType"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="tiaoVal == 8" label="设置温度">
          <el-input v-model="params" placeholder="请输入温度" />
        </el-form-item>
        <el-form-item v-if="tiaoVal == 15" label="设置声音">
          <el-input v-model="params" placeholder="请输入声音" />
        </el-form-item>
        
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogFillTiaoshi=false">
          取消
        </el-button>
        <el-button type="primary" @click="confirmTiao">
          确定
        </el-button>
      </div>
    </el-dialog>
    <Pagination :total="total" :page="page" @pagination="pagination" />
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { postDeviceFind, postDevice, putDevice, deleteDevice, getDevice, postDeviceCommand, postDeviceUnlock } from '@/api/Device'
import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
import { getDeviceGroup } from '@/api/DeviceGroup'
import { getMarketingTenant } from '@/api/MarketingTemplate'
import { getUser } from '@/api/user'
import { listArea, codeArea } from '@/api/Area'
import { getDeviceTemplate } from '@/api/DeviceTemplate'
import Pagination from '@/components/Pagination/index'

const defaultRole = {
  name: '',
  deviceTemplateId: '',
  sim: '',
  location: '',
  usage: '',
  status: '',
  tenantId: '',
  marketingTemplateId: '',
  userId: '',
  deviceGroupId: '',
  deviceSn:'',
  provinceCode:'',
  cityCode:'',
  regionCode:'',
  userName:'',
  userAccount:'',
  customProperties:[],
}
let id = 0;
export default {
  props:{
    // 如果该值为false 则只能选择最后一级 
    // 如果该值为true 则可以选择任意层级
    	changeOnSelect:{
			default:false
		}
  },
  data() {
    return {
      params:'',
      userId: '',
      tiaoshiType:[
        {value:5,name:'应用重启'},
        {value:6,name:'设备重启'},
        {value:7,name:'打开大锁'},
        {value:8,name:'设置机柜温度'},
        {value:9,name:'打开LED灯'},
        {value:10,name:'关闭LED灯'},
        {value:11,name:'打开制冷开关'},
        {value:12,name:'关闭制冷开关'},
        {value:13,name:'重力置零'},
        {value:14,name:'重力标定'},
        {value:15,name:'声音控制'},
        {value:16,name:'打开加热器'},
        {value:17,name:'关闭加热器'},
        // {value:13,name:'获取信号信息'},
        // {value:14,name:'获取定位信息'},
      ],
      mobanList:[],
      mobanList2:[],
      gongsiList:[],
      yingxiaoList:[],
      zerenrenList:[],
      fenzuList:[],
      yingxiaoList2:[],
      zerenrenList2:[],
      fenzuList2:[],
      shengshiquList:[],
      tiaoVal: '',
      //注册
      checkAll: false,
      checkedCities: ['上海', '北京'],
      cities: ['上海', '北京', '广州', '深圳'],
      isIndeterminate: true,
      cityOptions: ['上海', '北京', '广州', '深圳'],
      dialogFillTiaoshi: false,
      showCheck: false,
      role: Object.assign({}, defaultRole),
      routes: [],
      dataList: [],
      dialogVisible: false,
      dialogFillBuckle: false,
      dialogRefund: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      rules: {
        name: [
          { required: true, message: '请输入设备名称' },
        ],
        deviceSn: [
          { required: true, message: '请输入设备序列号' },
        ],
        location: [
          { required: true, message: '请输入设备点位名称' },
        ],
        tenantId: [
          { required: true, message: '请选择所属公司' },
        ],
        deviceTemplateId: [
          { required: true, message: '请选择设备模板' },
        ],
        marketingTemplateId: [
          { required: true, message: '请选择营销模板' },
        ],
        deviceGroupId: [
          { required: true, message: '请选择分组' },
        ],
        userId: [
          { required: true, message: '请选择责任人' },
        ],
        shengshiqu: [
          { required: true, message: '请选择省市区' },
        ],
      },
      total: 0,
      page: 0,
      formInline: {
        orderDate: '',        
        gongsiSel: '',
        leibieSel: "",
        yongtuSel: "",
        fenzuSel: "",
        zerenrenSel: "",
        shengshiquSel: "",
        yingxiaoSel: "",
      },
      devicesId:'',
      area1: '',
      area2: '',
    }
  },
  computed: {},
  components: { Pagination },
  mounted() {
    console.log(JSON.parse(localStorage.getItem('companyList')))
    setTimeout(()=>{
      this.gongsiList = JSON.parse(localStorage.getItem('companyList'));
      this.formInline.gongsiSel = this.gongsiList[0].id;
      this.initData();
      this.deviceGropList(1);
      this.marketTemplateList(1);
      this.userList(1);
      this.areaList();
    },100)
  },
  methods: {
    //列表
    initData(){
      var list = {
        "pageCount": 10,
        "page": this.page,
        "searchCriteria": {
          "tenantId": this.formInline.gongsiSel,
          "usage": this.formInline.yongtuSel,
          "status": this.formInline.leibieSel,
          "ownerId": this.formInline.zerenrenSel,
          // "deviceTemplateId": '',
          "marketingTemplateId": this.formInline.yingxiaoSel,
          "deviceGroupId": this.formInline.fenzuSel,
          "provinceCode": '',
          "cityCode": '',
          "regionCode": '',
          "name": "",
          "deviceSn": ''
        }
      };
      if(this.formInline.zerenrenSel == ''){
        delete list.searchCriteria.ownerId;
      }
      if(this.formInline.yingxiaoSel == ''){
        delete list.searchCriteria.marketingTemplateId;
      }
      if(this.formInline.fenzuSel == ''){
        delete list.searchCriteria.deviceGroupId;
      }
      if(this.formInline.yongtuSel == ''){
        delete list.searchCriteria.usage;
      }
      if(this.formInline.leibieSel == ''){
        delete list.searchCriteria.status;
      }
      postDeviceFind(list).then((res)=>{
        this.dataList = res.result.devices;
        this.total = res.result.totalCount;
      })
    },
    //切换公司
    companyTable(data){
      this.deviceGropList(1);
      this.marketTemplateList(1);
      this.userList(1,'');
    },
    tenantIdChange(){
      this.deviceGropList(2);
      this.deviceTemplateList(2);
      this.marketTemplateList(2)
      this.userList(2,'');
    },
    //设备分组
    deviceGropList(num){
      var id = num == 1?this.formInline.gongsiSel:this.role.tenantId;
      getDeviceGroup(id).then((res)=>{
        if(num == 1){
          this.fenzuList = res.result;
        }else{
          this.fenzuList2 = res.result;
        }
      })
    },
    //设备模板
    deviceTemplateList(num){
      var id = num == 1?this.formInline.gongsiSel:this.role.tenantId;
      getDeviceTemplate(id).then((res)=>{
        if(num == 1){
          this.mobanList = res.result;
        }else{
          this.mobanList2 = res.result;
        }
      })
    },
    //责任人列表
    userList(num,userId){
      var id = num == 1?this.formInline.gongsiSel:this.role.tenantId;
      getUser(id).then((res)=>{
        if(num == 1){
          this.zerenrenList = res.result;
        }else{
          this.zerenrenList2 = res.result;
        }
        if(num == 2 && userId){
          for(let i=0;i<res.result.length;i++){
            if(res.result[i].id == userId){
              this.userId = res.result[i].name;
            }
          }
        }
      })
    },
    //省
    areaList(){
      codeArea('100000').then((res)=>{
        console.log(res)
        this.shengshiquList = res.result;
        this.shengshiquList.map((item, index) => {
          for (let k in item) {
            if (!item[k]) {
              delete item[k]
            }
          }
          // 先让数据变成父级
          item.child = []
          // 手动创建字段表明当前索引 假设arrIndex值为'1-2-3' 即为options[1].child[2].child[3]
          item.arrIndex = index + ''
          // 将当前数据转成字符串放入对象里 当做value值
          item.main = JSON.stringify(item)
        })
      })
    },
    handleItemChange (val) {
      // 因为允许选择任意级,所以在向下选择时,会出现选择多个的情况,造成选中的合并成了一个数组,我这里只让他选择到第三层,页面上最多只会出现选择三个,如果超出了,直接return出去 不需要再动态加载下去了
      console.log(val)
      if(val.length == 3){
        if(this.dialogVisible){
          this.role.provinceCode = JSON.parse(val[0]).code;
          this.role.cityCode = JSON.parse(val[1]).code;
          this.role.regionCode = JSON.parse(val[2]).code;
        }else{
          this.formInline.shengshiquSel = val[2].code;
        }
      }
      if (val.length > 2) return
      //开门见山的说,每选中一个选项,相当于将本条数据push到val里,所以索引为val.length - 1的那一项必然是当前点击的那一项,哇 我他娘的可真是才思敏捷啊 
      val = JSON.parse(val[val.length - 1])
      console.log(this.role)
      //发送请求,是不是觉得和初始化用的同一个接口,然后还分两个事件有点冗余?写代码不累啊!
      codeArea(val.code).then(res => {
        let data = res.result
        //是不是有点迷糊 arrIndex哪来的?这玩意就是手动塞进去的索引
        let arrIndex = val.arrIndex
        data.map((item, index) => {
          // 手动创建字段表明当前索引 假设arrIndex值为'1-2-3' 即为options[1].child[2].child[3]
          item.arrIndex = arrIndex + '-' + index
          // 将当前数据转成字符串放入对象里 当做value值
          item.main = JSON.stringify(item)
          // 判断是否是第三层及以上
          if (item.arrIndex.split('-').length < 3) {
            item.child = []
          }
        })
        // 根据父元素的arrIndex判断塞到哪个父元素下
        arrIndex = arrIndex.split('-')
        // 首项键不是child 和for循环里区别开
        let a = this.shengshiquList[arrIndex[0]]
        for (let i = 1; i < arrIndex.length; i++) {
          a = a['child'][arrIndex[i]]
        }
        // 方法丑是丑了点...不过...真香
        this.$delete(a, 'child');
        this.$set(a, 'child', data)
      })
    },
    //营销模板
    marketTemplateList(num){
      var id = num == 1?this.formInline.gongsiSel:this.role.tenantId;
      getMarketingTenant(id).then((res)=>{
        this.yingxiaoList = res.result;
        if(num == 1){
          this.yingxiaoList = res.result;
        }else{
          this.yingxiaoList2 = res.result;
        }
      })
    },
    //获取责任人id和name
    getUserName(index){
      console.log(this.userId)
      console.log(index)
      var data = this.zerenrenList2[index];
      this.role.userId = data.id;
      this.role.userName = data.name;
      this.role.userAccount = data.account;
    },  
    //确定    
    async confirm(formName) {
      var list = this.role;
      if(!this.role.deviceTemplateId){
        delete list.deviceTemplateId;
      }
      if(!this.role.deviceGroupId){
        delete list.deviceGroupId;
      }
      if(!this.role.marketingTemplateId){
        delete list.marketingTemplateId;
      }
      if(!this.role.userId){
        delete list.userId;
      }
      if(this.dialogType == 'edit'){
        putDevice(this.devicesId,list).then((res)=>{
          this.dialogVisible = false;
          this.initData();
          this.$message({
            type: 'success',
            message: '编辑成功!'
          })
        })
      }else{
        this.$refs[formName].validate((valid) => {
          if (valid) {
            postDevice(list).then((res)=>{
              this.dialogVisible = false
              this.initData();
              this.$message({
                type: 'success',
                message: '创建成功!'
              })
            })
          }else{
            return
          }
        })
      }
    },
    //调试
    confirmTiao(){
      var list = {
        "deviceId": this.role.id,
        "deviceTemplateId": this.role.deviceTemplateId,
        "commandType": this.tiaoVal,
        "params": []
      }
      if(this.tiaoVal == 8 || this.tiaoVal == 15){
        list.params.push(this.params)
      }
      postDeviceCommand(list).then((res)=>{
        this.dialogFillTiaoshi = false;
        this.initData();
        this.$message({
          type: 'success',
          message: '成功!'
        })
      })
    },
    handleDelete(scope) {
      this.role = deepClone(scope.row);
      this.$confirm('确认删除?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          deleteDevice(this.role.id).then((res)=>{
            this.initData();
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        })
        .catch(err => { console.error(err) })
    },
    //重置
    handleReset(){
      this.role = Object.assign({}, defaultRole);
    },
    //查询
    checkMenu(){
      this.initData();
    },
    //过滤
    check(){
      this.showCheck = !this.showCheck;
    },
    //分页
    pagination(data) {
      this.initData();
    },
    handleAdd() { 
      this.role = Object.assign({}, defaultRole)     
      this.role.tenantId = this.gongsiList[0].id;
      this.userList(2,'');
      this.deviceTemplateList();
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope,index) {    
      this.deviceTemplateList();
      this.role = Object.assign({}, defaultRole) 
      this.devicesId = scope.row.id;
      console.log(scope.row)
      getDevice(scope.row.id).then((res)=>{
        var obj = res.result;
        Object.keys(this.role).forEach(key=>{this.role[key]=obj[key]});
        this.role.deviceTemplateId = obj.deviceTemplate.id;
        this.role.deviceGroupId = obj.group.id;
        this.role.marketingTemplateId = obj.marketingTemplate?obj.marketingTemplate.id:'';
        this.dialogType = 'edit'
        this.dialogVisible = true
        this.userList(2,obj.userId);
        this.marketTemplateList();
        this.deviceGropList();
      })
    },
    handleTiao(scope){
      this.role = Object.assign({}, defaultRole) 
      getDevice(scope.row.id).then((res)=>{
        var obj = res.result;
        Object.keys(this.role).forEach(key=>{this.role[key]=obj[key]});
        this.role.deviceTemplateId = obj.deviceTemplate.id;
        this.role.id = scope.row.id;
        this.role.marketingTemplateId = obj.marketingTemplate?obj.marketingTemplate.id:'';
        this.dialogFillTiaoshi = true
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
